<?php
require_once APP . '/application/controllers/FrontAction.php';

/**
 * 首页
 */
class SearchController extends FrontAction
{
    
    /**
     * 首页
     *
     */
    public function indexAction()
    {
    	$query = $this->getParam("query");
    	$total = (int)$this->getParam("total", 0);
    	$p = (int)$this->getParam("p", 1);
    	
    	$per_page = 10;
    	
    	$query = str_replace(array('%', '?', '"', '\''), '', $query);
    	$query = mysql_real_escape_string($query);

    	$sql = array();
    	$sql[] = '(select "news" as type, aid as id,title,content from article where title like "%' . $query . '%" order by seq desc,aid desc limit 30)';
    	
    	$sql[] = '(select "publication" as type, pid as id,name as title,intro as content from publication where name like "%' . $query . '%" order by seq desc,pid desc limit 20)';
    	
    	$sql[] = '(select "video" as type, vid as id,name as title,content from video where name like "%' . $query . '%" order by seq desc,vid desc limit 20)';
    	
    	$sql[] = '(select "images" as type, id,name as title,content from images where name like "%' . $query . '%" order by seq desc,id desc limit 20)';

    	if (empty($total)){
    		$countsql = 'select count(*) from (' . implode(" union ", $sql) . ') ttt';
    		$total = $this->db->fetchOne($countsql);
    	}
    	
    	$pageInfo = Util::page ($total, $per_page, $p);
        $start    = $pageInfo ['start'];
        
        $searchsql = 'select * from (' . implode(" union ", $sql) . ') tt2 order by id desc limit ' . $start . ',' . $per_page;
        $list = $this->db->fetchAll($searchsql);
        
       foreach ($list as $key => $v){
        	$content = strip_tags($v['content']);
        	$content = mb_cut($content, 200);
        	
        	$list[$key]['content'] = $content;
        	$list[$key]['title'] = strip_tags($v['title']);
        	$list[$key]['title'] = str_replace($query, '<span class="c_ora_red">' . $query . '</span>', $list[$key]['title']);
        	$list[$key]['stitle'] = strip_tags($v['title']);
        	
        	if ($v['type'] == 'news'){
        		$list[$key]['url'] = $this->url($this->baseUrl, "news", "detail", "aid=" . $v['id']);
        	}elseif ($v['type'] == 'publication'){
        		$list[$key]['url'] = $this->url($this->baseUrl, "publication", "detail", "pid=" . $v['id']);
        	}elseif ($v['type'] == 'video'){
        		$list[$key]['url'] = $this->url($this->baseUrl, "media", "detail", "vid=" . $v['id']);
        	}elseif ($v['type'] == 'images'){
        		$list[$key]['url'] = $this->url($this->baseUrl, "media", "detail", "id=" . $v['id']);
        	}
        }
    	
    	$this->view->query = $query;
    	
    	$this->view->list = $list;
    	$this->view->page = $pageInfo['page'];
    	$this->view->pagenum = Util::pageNumStyle($pageInfo['page']);
    	
    	$this->render("index");
    }
    
}
